package com.wen.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * 深度拷贝
 */
public class TestDeepCopy {

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三",18));
        A a = new A(list);
        A clone = a.clone();
        clone.getList().add(new Student("李四",20));
        System.out.println("目标对象的集合值有");
        for (Student s : a.getList()) {
            System.out.println(s.toString()+ "我的hash地址为"+s.hashCode());
        }
        System.out.println("拷贝后的对象值有");
        for (Student s : clone.getList()) {
            System.out.println(s.toString() + "我的hash地址为"+s.hashCode());
        }
        System.out.println(a.getList().get(0).equals(clone.getList().get(0)));
    }

    /**
     * cloneable  接口实现是为了给jvm提供一个标识  来表示这个类是可以在堆内存中进行复制的
     */
   static class A implements Cloneable{
        protected ArrayList<Student> list;
        public A() {
        }
        public A(ArrayList<Student> list) {
            this.list = list;
        }
        public List<Student> getList() {
            return list;
        }
        public void setList(ArrayList<Student> list) {
            this.list = list;
        }
        @Override
        public A clone() {
            A a = null;
            try {
                a = (A) super.clone();
                //这里是对集合再次进行拷贝
                this.list = (ArrayList<Student>) this.list.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            return a;
        }
    }

    /**
     * 实体测试类
     */
    static class Student{
        private String name;
        private Integer age;

        public Student(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public Student() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

